<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>头像合成</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" href="css/cropper.min.css">
    <link rel="stylesheet" href="css/ImgCropping.css">
    <style>
        img#imgdom {
            display: none;
        }
        
        canvas#compose {
            position: absolute;
            left: -1000px;
        }
        
        .head {
            font-size: 20px;
            text-align: center;
            font-weight: 600;
            padding: 20px;
            background-color: antiquewhite;
            color: #666666;
        }
        
        .wrap {
            min-width: 640px;
            width: 80%;
            margin: 5% auto;
            box-shadow: 0 0 1px;
            border-radius: 4px;
            overflow: hidden;
        }
        
        .wrap button {
            width: 100px;
        }
        
        .wrap input {
            outline: none;
            padding: 9px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        
        .btnWrap li {
            list-style: none;
            margin: 10px;
            line-height: 50px;
            height: 50px;
        }
        
        .checked label {
            margin-left: 25px;
        }
        
        input#checked {
            width: auto;
            margin-right: 14px;
            position: absolute;
            top: 20px;
        }
        
        .btnWrap li div {
            display: inline-block;
        }
        
        .SliderWrap {
            position: relative;
            margin-left: 30px;
        }
        
        .SliderWrap input {
            width: 25px;
            padding: 3px;
            text-align: center;
        }
        
        .SliderWrap label {
            font-size: 12px;
        }
        
        .btnWrap {
            padding: 20px;
            border-top: 1px solid #ccc;
            margin-top: 20px;
        }
        
        .imgWrap {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            flex-direction: column;
            align-items: center;
        }
        
        .imgWrap p {
            line-height: 35px;
            font-size: 14px;
            text-align: center;
            background-color: antiquewhite;
        }
        
        .imgWrap>* {
            box-shadow: 0 0 4px #ccc;
            height: 195px;
            width: 160px;
            position: relative;
            display: flex;
            flex-direction: column;
        }
        
        canvas {
            position: absolute;
            left: 0px;
            top: 0px;
        }
        
        .canvas>* canvas {
            height: 160px;
            width: 160px;
        }
        
        .canvas>div,
        .img>div {
            flex: 1;
            position: relative;
            background-size: cover;
        }
        
        .canvas>div::after {
            position: absolute;
            color: #ccc;
            left: 39px;
            top: 75px;
            font-size: 12px;
            z-index: -10;
        }
        
        .img>div::after {
            position: absolute;
            color: #ccc;
            left: 200px;
            top: 339px;
            font-size: 50px;
            z-index: -10;
        }
        
        .img>div::after {
            content: "显示下载比例头像";
        }
        
        .canvas>div::after {
            content: "显示合成后头像";
        }
        
        .imgWrap>* img {
            height: 160px;
            width: 160px;
        }
        
        .slider {
            position: absolute;
            width: 10px;
            height: 20px;
            top: 50%;
            background: #797979;
            margin-top: -10px;
            z-index: 1;
            cursor: pointer;
        }
        
        canvas#backgroundcanvas {
            z-index: 2;
        }
        
        canvas#canvas {
            z-index: -1;
        }
        
        canvas#Pendant1Canvas {
            z-index: 3;
        }
        
        canvas#Pendant0Canvas {
            z-index: 3;
        }
        
        canvas#uesrNameCanvas {
            z-index: 13;
        }
        
        canvas#uesrNameSubtitleCanvas {
            z-index: 13;
        }
        
        canvas#canvasScale {
            z-index: -1;
        }
        
        canvas#Pendant1CanvasScale {
            z-index: 3;
        }
        
        canvas#Pendant0CanvasScale {
            z-index: 3;
        }
        
        canvas#uesrNameCanvasScale {
            z-index: 13;
        }
        
        canvas#uesrNameSubtitleCanvasScale {
            z-index: 13;
        }
        
        input.distance[readonly] {
            background: #ccc;
        }
        
        .img div {
            flex: 1;
        }
        
        .img {
            margin-bottom: 20px;
        }
        
        @media screen and (max-width: 700px) {
            /*当屏幕尺寸小于700px时，应用下面的CSS样式*/
            body {
                background: linear-gradient(45deg, #0ca542, #aeb10b);
            }
            .wrap {
                min-width: auto;
                width: auto;
                margin: 10px;
                box-shadow: 0 0 1px #ccc;
                position: relative;
            }
            .canvas {
                position: relative;
            }
            .wrap::after,
            .canvas::after {
                position: absolute;
                background-color: #ffffff;
                width: 100%;
                height: 100%;
                content: "";
                top: 0;
                display: inline-block;
                z-index: -11;
            }
            .imgWrap {
                flex-direction: column;
                align-items: center;
            }
            .btnWrap li {
                height: auto;
                margin-left: 0px;
            }
            .btnWrap li div {
                display: block;
            }
            .fixed {
                position: fixed;
                top: 0;
                z-index: 1;
            }
            .imgbottom {
                margin-bottom: 195px;
            }
            .SliderWrap input {
                width: 50px;
            }
            .red {
                margin-left: 42px;
            }
            .img {
                display: none;
            }
        }
        
        .SliderWrap p {
            line-height: 20px;
            font-size: 12px;
        }
        
        .red {
            position: relative;
        }
        
        .red::after {
            position: absolute;
            content: "备注：";
            left: -43px;
            top: -13px;
            color: red;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="head">合成头像</div>
        <div class="imgWrap">
            <div class="img">
                <div>
                    <canvas id="uesrNameCanvasScale"></canvas>
                    <canvas id="uesrNameSubtitleCanvasScale"></canvas>
                    <canvas id="Pendant0CanvasScale"></canvas>
                    <canvas id="Pendant1CanvasScale"></canvas>
                    <canvas id="canvasScale"></canvas>
                    <canvas id="backgroundcanvasScale"></canvas>
                </div>
                <p>缩放头像预览</p>
            </div>
            <div class="canvas">
                <div>
                    <canvas id="uesrNameCanvas"></canvas>
                    <canvas id="uesrNameSubtitleCanvas"></canvas>
                    <canvas id="Pendant0Canvas"></canvas>
                    <canvas id="Pendant1Canvas"></canvas>
                    <canvas id="canvas"></canvas>
                    <canvas id="backgroundcanvas"></canvas>
                </div>
                <p>头像预览</p>
            </div>
        </div>

        <canvas id="compose" width="160px" height="160px"></canvas>
        <div class="btnWrap">
            <ul>

                <li class="uesrName">
                    <label for="uesrName">姓名：</label><input type="text" id="uesrName" placeholder="请输入姓名">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="37">
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="140">
                    </div>
                    <div class="SliderWrap">
                        <label for="">字体大小(px)：</label><input type="text" class="distance" value="15">
                    </div>
                </li>
                <li class="uesrNameSubtitle">
                    <label for="uesrNameSubtitle">职位：</label><input type="text" id="uesrNameSubtitle" placeholder="请输入职位">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="77">
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="140">
                    </div>
                    <div class="SliderWrap">
                        <label for="">字体大小(px)：</label><input type="text" class="distance" value="8">
                    </div>
                </li>
                <li>
                    <label for="">头像像素(px)：</label><input type="text" class="distance" id="scale" value="750" style="
                    width: 109px;
                    margin-right: 40px;
                ">
                    <div class="SliderWrap red">
                        <div style="color: red;">
                            <p>1、默认750px，下载头像尺寸为:750px*750px，大小可调整</p>
                            <p>2、移动端看不到下载头像的真实尺寸，只能看到预览头像图，电脑端可看到下载头像尺寸;</p>
                        </div>
                    </div>
                </li>
                <li>
                    <button id="replaceImg" class="l-btn">选择头像</button><input type="file" id="replaceImgFile" style="display: none;">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="90" readonly>
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="90" readonly>
                    </div>
                </li>
                <li class="background">
                    <button id="background" class="l-btn">选择背景图</button><input type="file" id="backgroundFile" style="display: none;">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="0" readonly>
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="0" readonly>
                    </div>
                    <div class="SliderWrap checked"><input type="checkbox" id="checked" checked><label for="checked">全图做背景</label></div>
                </li>
                <li class="img0">
                    <button id="img0" class="l-btn">选择挂件</button><input type="file" id="img0File" style="display: none;">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="50">
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="50">
                    </div>
                </li>
                <li class="img1" style="display: none;">
                    <button id="img1" class="l-btn">选择挂件2</button><input type="file" id="img1File" style="display: none;">
                    <div class="SliderWrap">
                        <label for="">左边距离(px)：</label><input type="text" class="distance" value="50">
                    </div>
                    <div class="SliderWrap">
                        <label for="">顶部距离(px)：</label><input type="text" class="distance" value="50">
                    </div>
                </li>
                <li>
                    <button id="downLoad" class="l-btn">下载</button><button id="composeBtn" class="l-btn" style="display: none;">合成</button>
                </li>
            </ul>
        </div>
    </div>
    <div style="display: none" class="tailoring-container">
        <div class="black-cloth" onclick="closeTailor(this)"></div>
        <div class="tailoring-content">
            <div class="tailoring-content-one">
                <label title="上传图片" for="chooseImg" class="l-btn choose-btn">
				<input type="file" accept="image/jpg,image/jpeg,image/png" name="file" id="chooseImg" class="hidden" onchange="selectImg(this)">
				选择图片
				</label>
                <div class="close-tailoring" onclick="closeTailor(this)">×</div>
            </div>
            <div class="tailoring-content-two">
                <div class="tailoring-box-parcel">
                    <img id="tailoringImg">
                </div>
                <div class="preview-box-parcel">
                    <p>图片预览：</p>
                    <div class="square previewImg"></div>
                    <div class="circular previewImg"></div>
                </div>
            </div>
            <div class="tailoring-content-three">
                <button class="l-btn cropper-reset-btn">复位</button>
                <button class="l-btn cropper-rotate-btn">旋转</button>
                <button class="l-btn cropper-scaleX-btn">换向</button>
                <button class="l-btn sureCut" id="sureCut">确定</button>
            </div>
        </div>

    </div>
    <img id="imgdom" />
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/cropper.min.js"></script>
    <script>
        //姓名 挂件1 挂件2 头像 背景  合成
        let _uesrNameCanvas = document.getElementById('uesrNameCanvas'),
            _uesrNameSubtitleCanvas = document.getElementById('uesrNameSubtitleCanvas'),
            _Pendant0Canvas = document.getElementById('Pendant0Canvas'),
            _Pendant1Canvas = document.getElementById('Pendant1Canvas'),
            _canvas = document.getElementById('canvas'),
            _backgroundcanvas = document.getElementById('backgroundcanvas'),
            _uesrNameCanvasScale = document.getElementById('uesrNameCanvasScale'),
            _uesrNameSubtitleCanvasScale = document.getElementById('uesrNameSubtitleCanvasScale'),
            _Pendant0CanvasScale = document.getElementById('Pendant0CanvasScale'),
            _Pendant1CanvasScale = document.getElementById('Pendant1CanvasScale'),
            _canvasScale = document.getElementById('canvasScale'),
            _backgroundcanvasScale = document.getElementById('backgroundcanvasScale'),
            _compose = document.getElementById('compose');

        let _length, _x, _y; //距离  鼠标的x轴 鼠标Y轴

        (function() {
            let _bodyW = document.body.clientWidth; //可视窗口宽度
            let _cW = $.trim($("#scale").val()); //比例canvas
            //console.log(_bodyW);
            //设置比例canvas宽，高
            _uesrNameCanvasScale.width = _cW;
            _uesrNameSubtitleCanvasScale.width = _cW;
            _Pendant0CanvasScale.width = _cW;
            _Pendant1CanvasScale.width = _cW;
            _canvasScale.width = _cW;
            _backgroundcanvasScale.height = _cW
            _uesrNameCanvasScale.height = _cW;
            _uesrNameSubtitleCanvasScale.height = _cW;
            _Pendant0CanvasScale.height = _cW;
            _Pendant1CanvasScale.height = _cW;
            _canvasScale.height = _cW;
            _backgroundcanvasScale.height = _cW;
            //设置父级box
            $(".img").css({
                width: parseInt(_cW),
                height: parseInt(_cW) + 35
            });
            //console.log(_bodyW < 800)
            // if (_bodyW < 800) {
            //     //console.log("display")
            //     $(".img").css("display", "none");
            // }
        })()
        //弹出框水平垂直居中
        // (window.onresize = function() {
        //     var win_height = $(window).height();
        //     var win_width = $(window).width();
        //     if (win_width <= 768) {
        //         $(".tailoring-content").css({
        //             "top": (win_height - $(".tailoring-content").outerHeight()) / 2,
        //             "left": 0
        //         });
        //     } else {
        //         $(".tailoring-content").css({
        //             "top": (win_height - $(".tailoring-content").outerHeight()) / 2,
        //             "left": (win_width - $(".tailoring-content").outerWidth()) / 2
        //         });
        //     }
        // })();



        //弹出图片裁剪框
        // $("#replaceImg").on("click", function() {
        //     $(".tailoring-container").toggle();
        // });
        //图像上传
        // function selectImg(file) {
        //     if (!file.files || !file.files[0]) {
        //         return;
        //     }
        //     var reader = new FileReader();
        //     reader.onload = function(evt) {
        //         var replaceSrc = evt.target.result;
        //         //更换cropper的图片
        //         $('#tailoringImg').cropper('replace', replaceSrc, false); //默认false，适应高度，不失真
        //     }
        //     reader.readAsDataURL(file.files[0]);
        // }
        // //cropper图片裁剪
        // $('#tailoringImg').cropper({
        //     aspectRatio: 1 / 1, //默认比例
        //     preview: '.previewImg', //预览视图
        //     guides: false, //裁剪框的虚线(九宫格)
        //     autoCropArea: 0.5, //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
        //     movable: false, //是否允许移动图片
        //     dragCrop: true, //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
        //     movable: true, //是否允许移动剪裁框
        //     resizable: true, //是否允许改变裁剪框的大小
        //     zoomable: true, //是否允许缩放图片大小
        //     mouseWheelZoom: true, //是否允许通过鼠标滚轮来缩放图片
        //     touchDragZoom: true, //是否允许通过触摸移动来缩放图片
        //     rotatable: true, //是否允许旋转图片
        //     crop: function(e) {
        //         // 输出结果数据裁剪图像。
        //     }
        // });
        // //旋转
        // $(".cropper-rotate-btn").on("click", function() {
        //     $('#tailoringImg').cropper("rotate", 90);
        // });
        // //复位
        // $(".cropper-reset-btn").on("click", function() {
        //     $('#tailoringImg').cropper("reset");
        // });
        // //换向
        // var flagX = true;
        // $(".cropper-scaleX-btn").on("click", function() {
        //     if (flagX) {
        //         $('#tailoringImg').cropper("scaleX", -1);
        //         flagX = false;
        //     } else {
        //         $('#tailoringImg').cropper("scaleX", 1);
        //         flagX = true;
        //     }
        //     flagX != flagX;
        // });

        //裁剪后的处理
        // $("#sureCut").on("click", function() {
        //     if ($("#tailoringImg").attr("src") == null) {
        //         return false;
        //     } else {
        //         var cas = $('#tailoringImg').cropper('getCroppedCanvas'); //获取被裁剪后的canvas
        //         var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
        //         //$("#finalImg").prop("src", base64url); //显示为图片的形式
        //         $("#finalImg").css("background-image", `url(${base64url})`); //显示为图片的形式

        //         //关闭裁剪框
        //         closeTailor();
        //     }

        //     var canvas = document.getElementById('canvas')
        //     canvas.width = 300
        //     canvas.height = 300
        //     var ctx = canvas.getContext('2d')
        //     var img = new Image()
        //     img.src = base64url
        //     img.onload = function() {
        //         // 通过arc来绘制一个圆形区域
        //         ctx.arc(150, 150, 70, 0, 2 * Math.PI)
        //         ctx.clip()
        //         ctx.drawImage(img, 90, 90, 140, 140)
        //     }
        // });
        //关闭裁剪框
        // function closeTailor() {
        //     $(".tailoring-container").toggle();
        // };


        //头像
        $("#replaceImg").click(function() {
            $("#replaceImgFile").click(); //点击背景文件选择控件
        });

        //头像选择后
        $("#replaceImgFile").change(function() {
            //console.log("头像选择后");
            var file = $(this)[0].files[0]; //获取文件信息
            // let _l = $("li.img0 .SliderWrap").eq(0).find("input").val();
            // let _t = $("li.img0 .SliderWrap").eq(1).find("input").val();
            // console.log(_l)
            // console.log(_t)
            _canvasFn(file);

            //比例头像
            _canvasFn(file, $.trim($("#scale").val()));
        });


        //生成头像
        let _canvasFn = (file, Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            if (file) {
                let reader = new FileReader(); //调用FileReader
                reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
                reader.onload = function(evt) { //读取操作完成时触发。
                    let img = new Image();
                    img.src = evt.target.result; //将img标签的src绑定为DataURL

                    //显示合成（默认160）
                    let ctx = _canvas.getContext('2d');
                    _canvas.width = 160;
                    _canvas.height = 160;

                    let ctxScale = _canvasScale.getContext('2d');
                    //比例合成
                    if (Object.prototype.toString.call(parseInt(Scale)) == "[object Number]") {
                        _canvasScale.width = parseInt(Scale);
                        _canvasScale.height = parseInt(Scale);
                    }

                    img.onload = function() {

                        if (Scale == 160) {
                            //生成显示头像（默认）
                            ctx.rect(0, 0, 160, 160);
                            ctx.fillStyle = "#fdfcf8";
                            ctx.fill();
                            ctx.arc(160, 160, 120, 0, 2 * Math.PI)
                            ctx.clip()
                            ctx.drawImage(img, 0, 0, _canvas.width, _canvas.height); //生成背景
                        } else {
                            //生成比例头像
                            //比例合成
                            if (Object.prototype.toString.call(parseInt(Scale)) == "[object Number]") {
                                _canvasScale.width = parseInt(Scale);
                                _canvasScale.height = parseInt(Scale);
                                let _Scale = Scale / 160; //比例因子
                                //console.log(Scale)
                                //console.log(_canvasScale.width)
                                ctxScale.rect(0, 0, Scale, Scale);
                                ctxScale.fillStyle = "#fdfcf8";
                                ctxScale.fill();
                                ctxScale.arc(160 * _Scale, 160 * _Scale, 120 * _Scale, 0, 2 * Math.PI)
                                ctxScale.clip()
                                ctxScale.drawImage(img, 0, 0, _canvasScale.width, _canvasScale.height); //生成背景
                            }
                        }
                    };
                };
            }
        }


        //生成挂件1
        $("#img0").click(function() {
            $("#img0File").click(); //点击背景文件选择控件
        });

        //生成挂件1后
        $("#img0File").change(function() {
            //console.log("生成挂件1后");
            var file = $(this)[0].files[0]; //获取文件信息
            let _l = $("li.img0 .SliderWrap").eq(0).find("input").val();
            let _t = $("li.img0 .SliderWrap").eq(1).find("input").val();
            //console.log(_l)
            //console.log(_t)
            _Pendant0CanvasFn(file, _l, _t);
            //比例挂件
            _Pendant0CanvasFn(file, _l, _t, $.trim($("#scale").val()));
        });


        //生成挂件1函数
        let _Pendant0CanvasFn = (file, left, top, Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            //console.log(left)
            if (file) {
                let reader = new FileReader(); //调用FileReader
                reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
                reader.onload = function(evt) { //读取操作完成时触发。
                    let img = new Image();
                    img.src = evt.target.result; //将img标签的src绑定为DataURL
                    //显示默认合成（160）
                    let ctx = _Pendant0Canvas.getContext('2d');
                    _Pendant0Canvas.width = 160;
                    _Pendant0Canvas.height = 160;

                    let ctxScale = _Pendant0CanvasScale.getContext('2d');
                    //合成比例图
                    if (Scale || Object.prototype.toString.call(parseInt(Scale)) == "[object Number]") {
                        _Pendant0CanvasScale.width = parseInt(Scale);
                        _Pendant0CanvasScale.height = parseInt(Scale);

                        //console.log(_Pendant0CanvasScale.height)
                    }
                    img.onload = function() {
                        //ctx.drawImage(img, 0, 0, _Pendant0Canvas.width, _Pendant0Canvas.height, left, top, _Pendant0Canvas.width, _Pendant0Canvas.height); //生成背景
                        //显示默认合成（160）
                        ctx.drawImage(img, 0, 0, _Pendant0Canvas.width, _Pendant0Canvas.height); //生成背景
                        if (Scale || Object.prototype.toString.call(Scale) == "[object Number]") {
                            //合成比例背景
                            ctxScale.drawImage(img, 0, 0, _Pendant0CanvasScale.width, _Pendant0CanvasScale.height); //生成背景
                        }
                    };
                };
            }
        }



        //生成挂件2
        $("#img1").click(function() {
            $("#img1File").click(); //点击背景文件选择控件
        });

        //生成挂件2后
        $("#img1File").change(function() {
            //console.log("生成挂件2后");
            var file = $(this)[0].files[0]; //获取文件信息
            let _l = $("li.img1 .SliderWrap").eq(0).find("input").val();
            let _t = $("li.img1 .SliderWrap").eq(1).find("input").val();
            _Pendant1CanvasFn(file, _l, _t);
            //比例挂件
            _Pendant1CanvasFn(file, _l, _t, $.trim($("#scale").val()));
        });


        //生成挂件2函数
        let _Pendant1CanvasFn = (file, left, top, Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            if (file) {
                let reader = new FileReader(); //调用FileReader
                reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
                reader.onload = function(evt) { //读取操作完成时触发。
                    let img = new Image();
                    img.src = evt.target.result; //将img标签的src绑定为DataURL
                    //显示默认合成
                    let ctx = _Pendant1Canvas.getContext('2d');
                    _Pendant1Canvas.width = 160;
                    _Pendant1Canvas.height = 160;
                    //比例合成

                    if (Scale || Object.prototype.toString.call(parseInt(Scale)) == "[object Number]") {
                        let ctxScale = _Pendant1CanvasScale.getContext('2d');
                        let _Scale = Scale / 160; //比例因子
                        _Pendant1CanvasScale.width = parseInt(Scale);
                        _Pendant1CanvasScale.height = parseInt(Scale);
                    }
                    img.onload = function() {
                        //显示默认合成（160）
                        ctx.drawImage(img, 0, 0, _Pendant1CanvasScale.width, _Pendant1CanvasScale.height, left, top, _Pendant1CanvasScale.width, _Pendant1CanvasScale.height); //生成背景
                        //显示比例合成
                        ctxScale.drawImage(img, 0, 0, _Pendant1CanvasScale.width, _Pendant1Canvas.heightScale, left * _Scale, top * _Scale, _Pendant1Canvas.widthScale, _Pendant1CanvasScale.height); //生成背景
                    };
                };
            }
        }

        //生成姓名
        $("#uesrName").keyup(function() {
            let _username = $.trim($("#uesrName").val());
            let _l = $("li.uesrName .SliderWrap").eq(0).find("input").val();
            let _t = $("li.uesrName .SliderWrap").eq(1).find("input").val();
            let _f = $("li.uesrName .SliderWrap").eq(2).find("input").val();
            _uesrNameCanvasFn(_username, _l, _t, _f);

            //比例姓名
            _uesrNameCanvasFn(_username, _l, _t, _f, $.trim($("#scale").val()));
        });

        //生成名字函数
        let _uesrNameCanvasFn = (username, left, top, _fontsize, Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            if ($.trim(username)) {
                //显示默认名字（30）
                let ctx = _uesrNameCanvas.getContext('2d');
                _uesrNameCanvas.width = 160
                _uesrNameCanvas.height = 160
                ctx.clearRect(0, 0, _uesrNameCanvas.width, _uesrNameCanvas.height); //清空画布
                ctx.font = "bold " + _fontsize + "px Arial";
                ctx.fillText(username, left, top);

                //显示比例名字
                let _Scale = Scale / 160; //比例因子
                let ctxScale = _uesrNameCanvasScale.getContext('2d');
                _uesrNameCanvasScale.width = parseInt(Scale)
                _uesrNameCanvasScale.height = parseInt(Scale)
                console.log(_uesrNameCanvasScale.width)
                console.log(Scale)
                console.log(_Scale)
                console.log(left * _Scale)
                console.log(_fontsize * _Scale)
                ctxScale.clearRect(0, 0, _uesrNameCanvasScale.width, _uesrNameCanvasScale.height); //清空画布
                ctxScale.font = "bold " + _fontsize * _Scale + "px Arial";
                ctxScale.fillText(username, left * _Scale, top * _Scale);
            }
        };


        //生成职位
        $("#uesrNameSubtitle").keyup(function() {
            let _username = $.trim($("#uesrNameSubtitle").val());
            let _l = $("li.uesrNameSubtitle .SliderWrap").eq(0).find("input").val();
            let _t = $("li.uesrNameSubtitle .SliderWrap").eq(1).find("input").val();
            let _f = $("li.uesrNameSubtitle .SliderWrap").eq(2).find("input").val();
            _uesrNameSubtitleCanvasFn(_username, _l, _t, _f);
            //比例职位
            _uesrNameSubtitleCanvasFn(_username, _l, _t, _f, $.trim($("#scale").val()));
        });

        //生成职位
        let _uesrNameSubtitleCanvasFn = (username, left, top, _fontsize, Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            if ($.trim(username)) {
                //显示默认文字
                let ctx = _uesrNameSubtitleCanvas.getContext('2d');
                _uesrNameSubtitleCanvas.width = 160
                _uesrNameSubtitleCanvas.height = 160
                ctx.clearRect(0, 0, _uesrNameSubtitleCanvas.width, _uesrNameSubtitleCanvas.height); //清空画布
                ctx.font = "bold " + _fontsize + "px Arial";
                ctx.fillText(username, left, top);

                //显示比例文字;
                let _Scale = Scale / 160; //比例因子
                let ctxScale = _uesrNameSubtitleCanvasScale.getContext('2d');
                _uesrNameSubtitleCanvasScale.width = parseInt(Scale);
                _uesrNameSubtitleCanvasScale.height = parseInt(Scale);
                console.log(left)
                ctxScale.clearRect(0, 0, _uesrNameSubtitleCanvasScale.width, _uesrNameSubtitleCanvasScale.height); //清空画布
                ctxScale.font = "bold " + _fontsize * _Scale + "px Arial";
                ctxScale.fillText(username, left * _Scale, top * _Scale);
            }
        };

        //选择背景
        $("#background").click(function() {
            $("#backgroundFile").click(); //点击背景文件选择控件
        });

        //选择背景后
        $("#backgroundFile").change(function() {
            //console.log("选择背景后");
            var file = $(this)[0].files[0]; //获取文件信息
            let _l = $("li.background .SliderWrap").eq(0).find("input").val();
            let _t = $("li.background .SliderWrap").eq(1).find("input").val();
            let _c = $("#checked").is(":checked");
            _backgroundcanvasFn(file, _l, _t, _c);
            //比例背景
            _backgroundcanvasFn(file, _l, _t, _c, $.trim($("#scale").val()));
        });


        //选择背景函数
        let _backgroundcanvasFn = (file, left, top, check, Scale) => {
            //console.log(Scale)
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]")
                Scale = 160;
            if (file) {
                let reader = new FileReader(); //调用FileReader
                reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
                reader.onload = function(evt) { //读取操作完成时触发。
                    let img = new Image();
                    img.src = evt.target.result; //将img标签的src绑定为DataURL
                    $("#imgdom").attr("src", evt.target.result)
                    let _w = $("#imgdom").width();
                    let _H = $("#imgdom").height();
                    //显示默认背景（160）
                    let ctx = _backgroundcanvas.getContext('2d');
                    _backgroundcanvas.width = 160;
                    _backgroundcanvas.height = 160;

                    //显示比例背景
                    let ctxScale = _backgroundcanvasScale.getContext('2d');
                    //console.log(img)
                    img.onload = function() {
                        if (check) {
                            //默认背景
                            if (Scale == 160)
                                ctx.drawImage(img, 0, 0, _backgroundcanvas.width, _backgroundcanvas.height); //生成背景
                            else {

                                _backgroundcanvasScale.width = parseInt(Scale);
                                _backgroundcanvasScale.height = parseInt(Scale);
                                let _Scale = Scale / 160; //比例因子
                                //console.log(_backgroundcanvasScale.width)
                                //console.log(_backgroundcanvasScale.height)
                                //比例背景
                                ctxScale.drawImage(img, 0, 0, _backgroundcanvasScale.width, _backgroundcanvasScale.height); //生成背景
                            }
                        } else {
                            //默认背景
                            if (Scale == 160)
                                ctx.drawImage(img, 0, 0, _w, _H, left, top, _w, _H); //生成背景
                            else {
                                _backgroundcanvasScale.width = parseInt(Scale);
                                _backgroundcanvasScale.height = parseInt(Scale);
                                let _Scale = Scale / 160; //比例因子
                                //console.log(_backgroundcanvasScale.width)
                                //console.log(_backgroundcanvasScale.height)
                                //比例背景
                                ctxScale.drawImage(img, 0, 0, _w, _H, left * _Scale, top * _Scale, _w, _H); //生成背景
                            }
                        }
                    };
                };
            }
        }

        //compose  合成 _uesrNameCanvas, _Pendant0Canvas, _Pendant1Canvas, _canvas, _backgroundcanvas, _compose
        $("#composeBtn").click(function() {
            //console.log("compose")
            composeBtnFn($.trim($("#scale").val())); //合成文件
        });

        //合同图片
        let composeBtnFn = (Scale) => {
            if (!Scale || Object.prototype.toString.call(parseInt(Scale)) != "[object Number]") {
                //console.log(Scale)
                //默认合成
                let ctx = _compose.getContext('2d');
                _compose.width = 160
                _compose.height = 160
                ctx.drawImage(_canvas, 0, 0, _compose.width, _compose.height); //合成头像
                ctx.drawImage(_backgroundcanvas, 0, 0, _compose.width, _compose.height); //合成背景
                ctx.drawImage(_Pendant0Canvas, 0, 0, _compose.width, _compose.height); //合成挂件1
                ctx.drawImage(_Pendant1Canvas, 0, 0, _compose.width, _compose.height); //合成挂件2
                ctx.drawImage(_uesrNameCanvas, 0, 0, _compose.width, _compose.height); //合成名字
                ctx.drawImage(_uesrNameSubtitleCanvas, 0, 0, _compose.width, _compose.height); //合成职位
            } else {
                //console.log(Scale)
                //比例合成
                let ctxScale = _compose.getContext('2d');
                _compose.width = Scale
                _compose.height = Scale
                ctxScale.drawImage(_canvasScale, 0, 0, _compose.width, _compose.height); //合成头像
                ctxScale.drawImage(_backgroundcanvasScale, 0, 0, _compose.width, _compose.height); //合成背景
                ctxScale.drawImage(_Pendant0CanvasScale, 0, 0, _compose.width, _compose.height); //合成挂件1
                ctxScale.drawImage(_Pendant1CanvasScale, 0, 0, _compose.width, _compose.height); //合成挂件2
                ctxScale.drawImage(_uesrNameCanvasScale, 0, 0, _compose.width, _compose.height); //合成名字
                ctxScale.drawImage(_uesrNameSubtitleCanvasScale, 0, 0, _compose.width, _compose.height); //合成职位
            }
        }

        //保存
        document.getElementById("downLoad").onclick = function() {

            composeBtnFn($.trim($("#scale").val())); //合成文件
            downLoad(saveAsPNG(_compose));
        }

        //保存
        function downLoad(url) {
            // console.log(url)
            // var oA = document.createElement("a");
            // oA.download = ''; // 设置下载的文件名，默认是'下载'
            // oA.href = url;
            // document.body.appendChild(oA);
            // oA.click();
            // oA.remove(); // 下载之后把创建的元素删除
            let aLink = document.createElement('a');
            let blob = this.base64ToBlob(url); //new Blob([content]);

            let evt = document.createEvent("HTMLEvents");
            evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
            aLink.download = "头像合成";
            aLink.href = URL.createObjectURL(blob);

            // aLink.dispatchEvent(evt);
            aLink.click()
        }

        //base64转blob
        function base64ToBlob(code) {
            let parts = code.split(';base64,');
            let contentType = parts[0].split(':')[1];
            let raw = window.atob(parts[1]);
            let rawLength = raw.length;

            let uInt8Array = new Uint8Array(rawLength);

            for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
            }
            return new Blob([uInt8Array], {
                type: contentType
            });
        }

        // 保存成png格式的图片
        function saveAsPNG(canvas) {
            return canvas.toDataURL("image/png");
        }


        //生成选择图像base64url
        let uploadImg = (file) => {
            //console.log(file);
            let _url = ``;
            let imgdata = '';
            if (file) {
                let reader = new FileReader(); //调用FileReader
                reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
                reader.onload = function(evt) { //读取操作完成时触发。
                    //console.log(evt.target.result)
                    _url = evt.target.result; //将img标签的src绑定为DataURL
                };
            }

            //console.log(_url);
            return _url;
        }


        //距离改动
        $("input[class=distance]").keyup(function() {
            if (!/^(\-|\+)?\d+(\.\d+)?$/.test($(this).val())) {
                $(this).val(0);
            }
            canvasFn($(this).parents("li").attr("class"));
        })

        //调用绘制函数 _uesrNameCanvas, _Pendant0Canvas, _Pendant1Canvas, _canvas, _backgroundcanvas
        let canvasFn = (str) => {
            let _left, _top, _c;
            switch (str) {
                case "uesrNameSubtitle":
                    //console.log(str)
                    _left = $("li.uesrNameSubtitle .SliderWrap").eq(0).find("input").val();
                    _top = $("li.uesrNameSubtitle .SliderWrap").eq(1).find("input").val();
                    _c = $("li.uesrNameSubtitle .SliderWrap").eq(2).find("input").val();
                    _uesrNameSubtitleCanvasFn($("#uesrNameSubtitle").val(), _left, _top, _c); //生成职位
                    _uesrNameSubtitleCanvasFn($("#uesrNameSubtitle").val(), _left, _top, _c, $.trim($("#scale").val())); //生成比例职位
                    break;
                case "uesrName":
                    //console.log(str)
                    _left = $("li.uesrName .SliderWrap").eq(0).find("input").val();
                    _top = $("li.uesrName .SliderWrap").eq(1).find("input").val();
                    _c = $("li.uesrName .SliderWrap").eq(2).find("input").val();
                    _uesrNameCanvasFn($("#uesrName").val(), _left, _top, _c); //生成姓名
                    _uesrNameCanvasFn($("#uesrName").val(), _left, _top, _c, $.trim($("#scale").val())); //生成比例姓名
                    break;
                case "background":
                    _left = $("li.background .SliderWrap").eq(0).find("input").val();
                    _top = $("li.background .SliderWrap").eq(1).find("input").val();
                    _c = $("#checked").is(":checked");
                    _backgroundcanvasFn($("#backgroundFile")[0].files[0], _left, _top, _c); //绘制背景函数
                    _backgroundcanvasFn($("#backgroundFile")[0].files[0], _left, _top, _c, $.trim($("#scale").val())); //绘制比例背景函数
                    break;
                case "img0":
                    _left = $("li.img0 .SliderWrap").eq(0).find("input").val();
                    _top = $("li.img0 .SliderWrap").eq(1).find("input").val();
                    _Pendant0CanvasFn($("#img0File")[0].files[0], _left, _top); //绘制挂件1函数
                    _Pendant0CanvasFn($("#img0File")[0].files[0], _left, _top, $.trim($("#scale").val())); //绘制比例挂件1函数
                    break;
                case "img1":
                    _left = $("li.img1 .SliderWrap").eq(0).find("input").val();
                    _top = $("li.img1 .SliderWrap").eq(1).find("input").val();
                    _Pendant1CanvasFn($("#img1File")[0].files[0], _left, _top); //绘制挂件2函数
                    _Pendant1CanvasFn($("#img1File")[0].files[0], _left, _top, $.trim($("#scale").val())); //绘制比例挂件2函数
                    break;
            }
        }

        //修改图片象素文本获得焦点
        let _scaleWidth = 0;
        let _scaleFlag = 0;
        $("#scale").focus(function() {
            _scaleWidth = $(".img").css("width");
            //console.log(_scaleWidth)
        });
        //修改图片象素
        $("#scale").keyup(function() {
            let _cW = $.trim($("#scale").val());
            //设置比例canvas宽，高
            _uesrNameCanvasScale.width = _cW;
            _uesrNameSubtitleCanvasScale.width = _cW;
            _Pendant0CanvasScale.width = _cW;
            _Pendant1CanvasScale.width = _cW;
            _canvasScale.width = _cW;
            _backgroundcanvasScale.height = _cW
            _uesrNameCanvasScale.height = _cW;
            _uesrNameSubtitleCanvasScale.height = _cW;
            _Pendant0CanvasScale.height = _cW;
            _Pendant1CanvasScale.height = _cW;
            _canvasScale.height = _cW;
            _backgroundcanvasScale.height = _cW;

            //生成职位
            let _leftS = $("li.uesrNameSubtitle .SliderWrap").eq(0).find("input").val();
            let _topS = $("li.uesrNameSubtitle .SliderWrap").eq(1).find("input").val();
            let _cS = $("li.uesrNameSubtitle .SliderWrap").eq(2).find("input").val();
            _uesrNameSubtitleCanvasFn($("#uesrNameSubtitle").val(), _leftS, _topS, _cS); //生成显示职位
            _uesrNameSubtitleCanvasFn($("#uesrNameSubtitle").val(), _leftS, _topS, _cS, $.trim($("#scale").val())); //生成比例职位

            //生成姓名
            let _left = $("li.uesrName .SliderWrap").eq(0).find("input").val();
            let _top = $("li.uesrName .SliderWrap").eq(1).find("input").val();
            let _c = $("li.uesrName .SliderWrap").eq(2).find("input").val();
            _uesrNameCanvasFn($("#uesrName").val(), _left, _top, _c); //生成显示姓名
            _uesrNameCanvasFn($("#uesrName").val(), _left, _top, _c, $.trim($("#scale").val())); //生成比例姓名

            //生成职位
            let _leftB = $("li.background .SliderWrap").eq(0).find("input").val();
            let _topB = $("li.background .SliderWrap").eq(1).find("input").val();
            let _cB = $("#checked").is(":checked");
            _backgroundcanvasFn($("#backgroundFile")[0].files[0], _leftB, _topB, _cB); //绘制显示背景函数
            _backgroundcanvasFn($("#backgroundFile")[0].files[0], _leftB, _topB, _cB, $.trim($("#scale").val())); //绘制比例背景函数

            //生成挂件1
            let _left0 = $("li.img0 .SliderWrap").eq(0).find("input").val();
            let _top0 = $("li.img0 .SliderWrap").eq(1).find("input").val();
            _Pendant0CanvasFn($("#img0File")[0].files[0], _left0, _top0, $.trim($("#scale").val())); //绘制显示挂件1函数          
            _Pendant0CanvasFn($("#img0File")[0].files[0], _left0, _top0, $.trim($("#scale").val())); //绘制比例挂件1函数          

            //生成挂件2
            let _left1 = $("li.img1 .SliderWrap").eq(0).find("input").val();
            let _top1 = $("li.img1 .SliderWrap").eq(1).find("input").val();
            _Pendant1CanvasFn($("#img1File")[0].files[0], _left1, _top1, $.trim($("#scale").val())); //绘制比例挂件2函数
            _Pendant1CanvasFn($("#img1File")[0].files[0], _left1, _top1); //绘制显示挂件2函数

            //生成头像
            _canvasFn($("#replaceImgFile")[0].files[0], $.trim($("#scale").val()));
            _canvasFn($("#replaceImgFile")[0].files[0]);


            //设置父级box
            $(".img").css({
                width: parseInt(_cW),
                height: parseInt(_cW) + 35
            });

            //设置伪类样式
            _scaleFlag = parseInt($(this).val()) / parseInt(_scaleWidth);
            $('.img').append(`<style>.img div::after{display:none}</style>`);


        })

        //到顶部的距离
        let _st,
            _dot = $(".canvas").offset().top;
        $(document).scroll(function() {
            _st = $(document).scrollTop();
            if (_st >= _dot) {
                $(".canvas").addClass("fixed");
                $(".imgWrap").addClass("imgbottom");
            } else {
                $(".canvas").removeClass("fixed");
                $(".imgWrap").removeClass("imgbottom");
            }
        })

        //背景全屏
        $("#checked").change(function() {
            //console.log($(this).is(":checked"))
            if ($(this).is(":checked")) {
                $(this).parent().siblings().find("input").attr("readonly", true)
            } else {
                $(this).parent().siblings().find("input").removeAttr("readonly")
            }
            canvasFn("background"); //绘制背景
        })

        console.log(navigator)
    </script>
</body>

</html>